<template>
    <div class="container" v-loading="loading">
        <el-form ref="form" :model="filterForm">
            <el-form-item>
                <el-button class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate('')"
                           style="float: left;margin-right: 20px;">新增订单
                </el-button>
                <el-date-picker
                        type="date"
                        placeholder="选择开始日期"
                        v-model="filterForm.startDate"
                        style="width: 150px;"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-date-picker
                        type="date"
                        placeholder="选择结束日期"
                        v-model="filterForm.endDate"
                        style="width: 150px; margin-left: 10px;"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-select
                        v-model="filterForm.type"
                        filterable
                        clearable
                        placeholder="请选择订单类型"
                        class='normal-input'
                        style="width: 150px; margin-left: 10px;">
                    <el-option
                            v-for="item in types"
                            :key='item.value'
                            :label='item.name'
                            :value='item.value'>
                    </el-option>
                </el-select>
                <el-input clearable placeholder="请输入订单编号" v-model="filterForm.companyName"
                          style="width: 150px;margin-left: 10px;"></el-input>
                <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter(0)"
                           style="margin-left: 10px;">筛选
                </el-button>
                <el-button class="filter-item" type="primary" plain icon="el-icon-refresh" @click="handleFilter(1)"
                           style="margin-left: 10px;">重置
                </el-button>
         <!--       <el-button type="text" v-text="zsNum" style="margin-left: 10px;"></el-button>
                <el-button type="text" v-text="chNum" style="margin-left: 10px;"></el-button>-->
            </el-form-item>
        </el-form>
        <el-table :data="orderList" border fit stripe
                  style="width: 100%;">
            <el-table-column prop="id" align="center" label="编号" width="0" v-if="false">
            </el-table-column>
            <el-table-column prop="orderNum" align="center" label="订单编号" width="150">
            </el-table-column>
            <el-table-column prop="country" align="center" min-width="150px" label="外商国别" sortable>
            </el-table-column>
            <el-table-column prop="orderDate" align="center" min-width="150px" label="订单日期" sortable>
            </el-table-column>
            <el-table-column prop="deliveryDate" align="center" min-width="150px" label="交货日期" sortable>
            </el-table-column>
            <el-table-column prop="Customs" align="center" min-width="150px" label="报关地海关" sortable>
            </el-table-column>
            <el-table-column prop="amount" align="center" min-width="150px" label="总金额" sortable>
            </el-table-column>
            <el-table-column prop="currency" align="center" min-width="100px" label="币种" sortable>
            </el-table-column>
            <el-table-column prop="status" align="center" min-width="100px" label="状态" :filter-method="filterTag"
                             :filters="[{text:'中止订单',value:'中止订单'},
                             {text:'备货订单',value:'备货订单'},{ text: '在手订单',
                              value: '在手订单' }, { text: '出货订单', value: '出货订单' }]"
                             filter-placement="bottom-end">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status=='在手订单'" type="primary" disable-transitions>{{scope.row.status}}</el-tag>
                    <el-tag v-else-if="scope.row.status=='出货订单'" type="success" disable-transitions>{{scope.row.status}}</el-tag>
                    <el-tag v-else-if="scope.row.status=='备货订单'" type="info" disable-transitions>{{scope.row.status}}</el-tag>
                    <el-tag v-else type="warning" disable-transitions>{{scope.row.status}}</el-tag>
                </template>
                >
            </el-table-column>
            <el-table-column width="260px" label="操作">
                <template slot-scope="scope">
                    <el-button align="center" size="small" type="primary" plain @click="handleCreate(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.status =='在手订单'" size="small" type="danger" plain @click="oneExportHandle(scope.row)">一键出货</el-button>
                    <el-button align="center" size="small" type="success" plain @click="orderCopyHandle(scope.row)">复制订单</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background
                           layout='total, prev, pager, next'
                           :total='total'
                           :page-count='count'
                           :page-size='size'
                           :current-page='pageCurrent'
                           @current-change='handleCurrentChange'>
            </el-pagination>
        </div>
    </div>
</template>
<script>
    import {getOrderList, getOrderSearch, getOrderCount,copyOrderFn,oneExport} from '@/api/order';
    export default {
        data() {
            return {
                companyID: '',
                filterForm: {
                    startDate: '',
                    endDate: '',
                    type: '',
                    companyName: ''
                },
                types: [
                    /*{
                        value: '0',
                        name: '备货订单'
                    },*/
                    {
                        value: '1',
                        name: '在手订单'
                    },
                    {
                        value: '2',
                        name: '出货订单'
                    }
                ],
                zsNum: '在手订单总数:',
                chNum: '出货订单总数:',
                orderList: [],
                filter: false,
                total: 0,
                count: 0,
                pageCurrent: 1,
                size: 10,
                loading: false
            };
        },
        watch: {
            $route(to, from) {
                console.log(from);
                var orderid = to;
                if (orderid.name == 'Orderlist') {
                    var myInfo = JSON.parse(localStorage.getItem('UserInfo'));
                    if (myInfo == '"{}"' || myInfo == '{}') {
                        this.getOrderInfoList(this.companyID, '1');
                    } else {
                        this.companyID = myInfo.companyId;
                        this.getOrderInfoList(this.companyID, '1');
                    }
                }
            }
        },
        created() {

            var myInfo = JSON.parse(localStorage.getItem('UserInfo'));
            if (myInfo == '"{}"' || myInfo == '{}') {
                this.getOrderInfoList(this.companyID, '1');
            } else {
                this.companyID = myInfo.companyId;
                this.getOrderInfoList(this.companyID, '1');
            }
        },
        methods: {
            /**
              一键出货
            **/
            oneExportHandle(row){
                let that = this;
                let id = row.id;
                let _type = row.status;
                console.log(_type)
                console.log(row)
                if(_type == '备货订单'){
                    this.$message.error('当前订单为备货订单，不能一键出货');
                    return;
                }else if(_type == '出货订单'){
                    this.$message.error('当前订单已经是出货订单了，不能一键出货');
                    return;
                };
                if(!id){
                    this.$message.error("缺少id");
                    return;
                }else{
                    let applicationState = 2;
                    oneExport(id,applicationState).then(res=>{
                       if(res.code ==0){
                           this.$message({
                               type:'success',
                               message:'操作成功'
                           })
                           var myInfo = JSON.parse(localStorage.getItem('UserInfo'));
                           if (myInfo == '"{}"' || myInfo == '{}') {
                               that.getOrderInfoList(this.companyID, '1');
                           } else {
                               that.companyID = myInfo.companyId;
                               that.getOrderInfoList(this.companyID, '1');
                           }
                       }else{
                           this.$message.error(res.msg);
                       }
                    })
                }
            },
            filterTag(value, row) {
                return row.status === value;
            },
            handleFilter(type) {
                if (type == 0) {
                    this.filter = true;
                    this.getOrderSearch('1');
                } else {
                    this.filter = false;
                    this.filterForm.type = '';
                    this.filterForm.startDate = '';
                    this.filterForm.endDate = '';
                    this.getOrderInfoList(this.companyID, '1');
                }
            },
            // 当前的页码，改变时会触发
            handleCurrentChange: function (currentPage) {
                if (this.filter == true) {
                    this.getOrderSearch(currentPage);
                } else {
                    this.getOrderInfoList(this.companyID, currentPage);
                }
            },
            handleCreate(row) {
                let that = this;
                if (row === null || row == '') {
                    if (localStorage.hasOwnProperty('orderID')) {
                        localStorage.removeItem('orderID');
                    }
                    this.$router.push({
                        path: '/ordercreate',
                        query: {id: Math.random()}
                    });
                } else {
                    localStorage.setItem('orderID', row.id);
                    this.$router.push({path: '/ordercreate', query: {id: row.id}});

                    /* if (row.status == '在手订单' || row.status == '备货订单') {
                       localStorage.setItem('orderID', row.id);
                       this.$router.push({ path: '/ordercreate', query: { id: row.id } });
                     } else {
                       that.$message.error('已申报订单不能修改！');
                     }*/
                }
            },
            orderCopyHandle(row){
              let that = this;

              if(row&&row.id){
                  this.$confirm('您即将复制此订单, 是否继续?', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                  }).then(() => {
                      copyOrderFn(row.id).then(res=>{
                          if(res.code==0){
                              this.$message({
                                  type: 'success',
                                  message: '复制成功!'
                              });
                              this.$router.go(0)
                          }else{
                              this.$message.error(res.msg)
                          }
                      })

                  }).catch(() => {
                      this.$message({
                          type: 'info',
                          message: '已取消复制'
                      });
                  })

              }else{
                  this.$message.error('出错啦，请重新登陆或刷新页面')
              }
            },
            //初始化数据
            getOrderInfoList(companyID, page) {
                let that = this;
                that.loading = true;
                getOrderList(companyID, page)
                    .then(data => {
                        that.loading = false;
                        var myData = data.data;
                        if (myData.length <= 0) {
                            var lenth = this.orderList.length;
                            that.orderList.splice(0, lenth);
                        } else {
                            lenth = this.orderList.length;
                            that.orderList.splice(0, lenth);
                            //加入数据内容
                            for (let i of myData) {
                                var map = {
                                    id: i.id,
                                    orderNum: i.orderCodeCmp,
                                    computerName: i.companyHsName,
                                    country: i.foreignCountry,
                                    orderDate: i.orderTime,
                                    deliveryDate: i.deliveryTime,
                                    Customs: i.declareCustoms,
                                    amount: i.totalPrice,
                                    currency: i.orderCurrency,
                                    status: ''
                                };
                                if (i.applicationState == '0') {
                                    map.status = '备货订单';
                                } else if (i.applicationState == '1') {
                                    map.status = '在手订单';
                                } else if(i.applicationState == '2'){
                                    map.status = '出货订单';
                                }else if(i.applicationState == '3'){
                                    map.status = '中止订单';
                                }
                                that.orderList.push(map);
                            }
                            var page = data.page;
                            that.total = page.resultCount;
                            that.count = page.pageCount;
                            that.pageCurrent = page.pageCurrent;
                            that.size = page.pageLimit;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        that.loading = false;
                    });
                //取总数
                getOrderCount(companyID)
                    .then(data => {
                        var myData = data.data;
                        that.zsNum = '在手订单总数:' + myData.handOrderNum;
                        that.chNum = '出货订单总数:' + myData.outOrderNum;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            getOrderSearch(page) {
                let that = this;
                that.loading = true;
                getOrderSearch(
                    that.filterForm.startDate,
                    that.filterForm.endDate,
                    that.filterForm.type,
                    page,
                    that.filterForm.companyName
                )
                    .then(data => {
                        that.loading = false;
                        var myData = data.data;
                        if (myData.length <= 0) {
                            var lenth = that.orderList.length;
                            that.orderList.splice(0, lenth);
                        } else {
                            lenth = that.orderList.length;
                            that.orderList.splice(0, lenth);
                            //加入数据内容
                            for (let i of myData) {
                                var map = {
                                    id: i.id,
                                    orderNum: i.orderCodeCmp,
                                    computerName: i.companyHsName,
                                    country: i.foreignCountry,
                                    orderDate: i.orderTime,
                                    deliveryDate: i.deliveryTime,
                                    Customs: i.declareCustoms,
                                    amount: i.totalPrice,
                                    currency: i.orderCurrency,
                                    status: i.applicationState == '1' ? '在手订单' : '出货订单'
                                };
                                that.orderList.push(map);
                            }
                            var page = data.page;
                            that.total = page.resultCount;
                            that.count = page.pageCount;
                            that.pageCurrent = page.pageCurrent;
                            that.size = page.pageLimit;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        that.loading = false;
                    });
            }
        }
    };
</script>
<style>

</style>
